package com.duowan.cms.rpst.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.duowan.cms.common.repository.AbstractDomainObjectRepository;
import com.duowan.cms.common.repository.SQLParameterPair;
import com.duowan.cms.common.repository.SQLParameterPair.SQLOperateType;
import com.duowan.cms.common.util.ChineseCharactersUtil;
import com.duowan.cms.domain.user.UserPower;
import com.duowan.cms.domain.user.rpst.UserPowerRepository;
import com.duowan.cms.dto.user.UserPowerInfo;
import com.duowan.cms.dto.user.UserPowerSearchCriteria;

public class UserPowerRepositoryImpl extends AbstractDomainObjectRepository<UserPower, UserPowerInfo, UserPowerSearchCriteria> implements UserPowerRepository {
    
    protected Class<UserPower> getDomainObjectClass() {
        return UserPower.class;
    }
    
    @Override
    public UserPower getByUserIdAndChannelId(String userId, String channelId) {
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channelId", channelId);
        map.put("userId", userId);
        
        return selectOne(getPrefix() + ".getByUserIdAndChannelId", map);
        
    }
    
    @Override
    public List<UserPowerInfo> getAllPowerByUserId(String userId) {
        
        List<UserPowerInfo> list = selectList(getPrefix() + ".getAllPowerByUserId", userId);
        
        Collections.sort(list, new Comparator<UserPowerInfo>(){
            @Override
            public int compare(UserPowerInfo o1, UserPowerInfo o2) {
                String name1 = ChineseCharactersUtil.String2Alpha(o1.getChannelInfo().getName());
                String name2 = ChineseCharactersUtil.String2Alpha(o2.getChannelInfo().getName());
                return name1.compareTo(name2);
            }
        });
        
        return list;
    }
    
    public int deleteByIds(List<Serializable> ids) {
        
        List<SQLParameterPair> list = new ArrayList<SQLParameterPair>();
        for(Serializable userId : ids) {
            list.add(new SQLParameterPair(getPrefix() + ".deleteByUserId", userId, SQLOperateType.DELETE));
        }
        updateList(list);
        return 0;
    }
    
    @Override
    public void deleteByUserId(String userId) {
        updateOne(new SQLParameterPair(getPrefix() + ".deleteByUserId", userId, SQLOperateType.DELETE));
    }
    
    @Override
    public void updateUserPowerInAllChannles(UserPower userPower) {
        
        updateOne(new SQLParameterPair(getPrefix() + ".updateUserPowerInAllChannles", userPower, SQLOperateType.UPDATE));
    }
    
    
    @Override
    public void saveList(List<UserPower> list) {
        if(null == list || list.isEmpty())
            return ;
        updateOne(new SQLParameterPair(getPrefix() + ".saveList", list, SQLOperateType.INSERT));
    }
}
